<template>
  <view class="confetti-container" ref="confettiContainer">
    <view
      v-for="(item, index) in confettiList"
      :key="index"
      class="confetti"
      :style="{
        backgroundColor: item.color,
        width: item.size + 'px',
        height: item.size + 'px',
        left: item.left + '%',
        transform: `rotate(${item.rotation}deg)`,
        animationDelay: item.delay + 's',
        animationDuration: item.duration + 's',
      }"
    ></view>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";

const confettiList = ref<any>([]);
const instance = getCurrentInstance();

// 创建彩纸效果
function createConfetti() {
  const colors = [
    "#7C3AED",
    "#EC4899",
    "#3B82F6",
    "#10B981",
    "#F59E0B",
    "#EF4444",
  ];
  const count = 150;
  const list = [];
  for (let i = 0; i < count; i++) {
    list.push({
      color: colors[Math.floor(Math.random() * colors.length)],
      size: Math.random() * 10 + 5,
      left: Math.random() * 100,
      rotation: Math.random() * 360,
      delay: Math.random() * 5,
      duration: Math.random() * 3 + 2,
    });
  }
  confettiList.value = list;
  setTimeout(() => {
    confettiList.value = [];
  }, 5000);
}

// 获取容器信息
function getContainerInfo() {
  return new Promise((resolve) => {
    const query = uni.createSelectorQuery().in(instance);
    query
      .select(".confetti-container")
      .boundingClientRect((data) => {
        resolve(data);
      })
      .exec();
  });
}

function closeConfetti() {
  confettiList.value = [];
}

// 暴露方法给父组件
defineExpose({
  createConfetti,
  getContainerInfo,
  closeConfetti,
});
</script>

<style>
.confetti-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  overflow: hidden;
  z-index: 9999;
}
.confetti {
  position: absolute;
  top: -20px;
  /* border-radius: 50%; */
  animation: confetti-fall linear forwards;
}
@keyframes confetti-fall {
  0% {
    transform: translateY(-10px) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(100vh) rotate(720deg);
    opacity: 0;
  }
}
</style>
